package com.ruoyi.buy.service.impl;

import com.ruoyi.buy.domain.entity.PO.BuyRequestbuyBill;
import com.ruoyi.buy.domain.entity.PO.BuyRequestbuyBillItem;
import com.ruoyi.buy.domain.entity.buy0008.Buy0008GetInfoByIdVO;
import com.ruoyi.buy.mapper.PO.BuyRequestbuyBillItemMapper;
import com.ruoyi.buy.mapper.PO.BuyRequestbuyBillMapper;
import com.ruoyi.buy.service.IBuyRequestbuyBillService;
import com.ruoyi.buy.service.ICommonService;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 请购单Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-06-13
 */
@Service
@Transactional
public class BuyRequestbuyBillServiceImpl implements IBuyRequestbuyBillService
{
    @Resource
    private BuyRequestbuyBillMapper buyRequestbuyBillMapper;

    @Autowired
    private ICommonService iCommonService;

    @Resource
    private BuyRequestbuyBillItemMapper buyRequestbuyBillItemMapper;

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 查询请购单
     * 
     * @param id 请购单主键
     * @return 请购单
     */
    @Override
    public BuyRequestbuyBill selectBuyRequestbuyBillById(Long id)
    {
        return buyRequestbuyBillMapper.selectBuyRequestbuyBillById(id);
    }

    /**
     * 查询请购单列表
     * 
     * @param buyRequestbuyBill 请购单
     * @return 请购单
     */
    @Override
    public List<BuyRequestbuyBill> selectBuyRequestbuyBillList(BuyRequestbuyBill buyRequestbuyBill)
    {
        return buyRequestbuyBillMapper.selectBuyRequestbuyBillList(buyRequestbuyBill);
    }

    /**
     * 新增请购单
     * 
     * @param buyRequestbuyBill 请购单
     * @return 结果
     */
    @Override
    public int insertBuyRequestbuyBill(BuyRequestbuyBill buyRequestbuyBill)
    {
        buyRequestbuyBill.setCreateTime(DateUtils.getNowDate());
        return buyRequestbuyBillMapper.insertBuyRequestbuyBill(buyRequestbuyBill);
    }

    /**
     * 修改请购单
     * 
     * @param buyRequestbuyBill 请购单
     * @return 结果
     */
    @Override
    public int updateBuyRequestbuyBill(BuyRequestbuyBill buyRequestbuyBill)
    {
        buyRequestbuyBill.setUpdateTime(DateUtils.getNowDate());
        return buyRequestbuyBillMapper.updateBuyRequestbuyBill(buyRequestbuyBill);
    }

    /**
     * 批量删除请购单
     * 
     * @param ids 需要删除的请购单主键
     * @return 结果
     */
    @Override
    public int deleteBuyRequestbuyBillByIds(Long[] ids)
    {
        return buyRequestbuyBillMapper.deleteBuyRequestbuyBillByIds(ids);
    }

    /**
     * 删除请购单信息
     * 
     * @param id 请购单主键
     * @return 结果
     */
    @Override
    public int deleteBuyRequestbuyBillById(Long id)
    {
        return buyRequestbuyBillMapper.deleteBuyRequestbuyBillById(id);
    }

    @Override
    public void importData(MultipartFile file) throws IOException {


        File convFile = convertMultipartFileToFile(file);
        InputStream in = new FileInputStream(convFile);
        // 读取整个Excel
        XSSFWorkbook sheets = new XSSFWorkbook(in);
        // 获取第一个表单Sheet
        XSSFSheet sheetAt = sheets.getSheetAt(0);
        // 第四行请购日期 部门流水号  请购单编号
        XSSFRow titleRow = sheetAt.getRow(3);
        XSSFCell titleCell = titleRow.getCell(1);
        String titleStr = titleCell.getStringCellValue();

        //请购日期
        int partIndex =  titleStr.indexOf("部门流水号");
        String dateWithNull = titleStr.substring(5,partIndex);
        String vDate = dateWithNull.trim();
        //部门流水号
        int billIndex =  titleStr.indexOf("请购单编号");
        String partNoWithNull = titleStr.substring(partIndex+6,billIndex);
        String vPartNo = partNoWithNull.trim();
        //请购单编号
        //部门流水号
        int nIndex =  titleStr.indexOf("\n");
        String billWithNull = titleStr.substring(billIndex+6,nIndex);
        String vBillNo = billWithNull.trim();

        //处理请购单主要信息
        BuyRequestbuyBill requestbuyBill = new BuyRequestbuyBill();
        requestbuyBill.setdRequest(DateUtils.parseDate(vDate));
        requestbuyBill.setvBillNo(vBillNo);
        requestbuyBill.setvPartNo(vPartNo);
        requestbuyBill.setApplyBy(iCommonService.getUsername());
        requestbuyBill.setCreateBy(iCommonService.getUsername());
        requestbuyBill.setCreateTime(DateUtils.getNowDate());
        this.buyRequestbuyBillMapper.insertBuyRequestbuyBill(requestbuyBill);
        //那nmainid
        Long nMainId = this.buyRequestbuyBillMapper.selectBuyRequestbuyBillList(requestbuyBill).get(0).getId();

        //处理子项：从第六行开始，一直到项目相关行，中间都是请购单明细，如果名称型号品牌为空，那么直接默认为该行为空
        int lastRow = 0;
        List<BuyRequestbuyBillItem> buyRequestbuyBillItems = new ArrayList<>();
        for (int i = 5; i < sheetAt.getLastRowNum()+1; i++) {
            XSSFRow row = sheetAt.getRow(i);
            XSSFCell cell = row.getCell(1);
            String cellValue = getCellValue(cell,sheets);
            if (cellValue.indexOf("项目相关") != -1){
                break;
            }else{
                //如果品牌名称型号连续为空，这行就直接跳过
                cell = row.getCell(4);
                String nameValue = getCellValue(cell,sheets);
                cell = row.getCell(5);
                String modelValue = getCellValue(cell,sheets);
                cell = row.getCell(6);
                String brandValue = getCellValue(cell,sheets);
                if(StringUtils.isEmpty(nameValue) && StringUtils.isEmpty(modelValue) && StringUtils.isEmpty(brandValue) ){
                    continue;
                }else{
                    BuyRequestbuyBillItem buyRequestbuyBillItem = this.getBuyRequestBuyItem(row);
                    buyRequestbuyBillItem.setnMainId(nMainId);
                    buyRequestbuyBillItem.setStatus("0");
                    buyRequestbuyBillItem.setCreateBy(iCommonService.getUsername());
                    buyRequestbuyBillItem.setCreateTime(DateUtils.getNowDate());
                    buyRequestbuyBillItem.setnInvQty(BigDecimal.ZERO);
                    this.buyRequestbuyBillItemMapper.insertBuyRequestbuyBillItem(buyRequestbuyBillItem);
                }
            }
        }
    }

    @Override
    public Buy0008GetInfoByIdVO getInfo(Long id) {
        BuyRequestbuyBill buyRequestbuyBill = this.buyRequestbuyBillMapper.selectBuyRequestbuyBillById(id);
        BuyRequestbuyBillItem buyRequestbuyBillItem = new BuyRequestbuyBillItem();
        buyRequestbuyBillItem.setnMainId(id);
        List<BuyRequestbuyBillItem> buyRequestbuyBillItems = this.buyRequestbuyBillItemMapper.selectBuyRequestbuyBillItemList(buyRequestbuyBillItem);
        Buy0008GetInfoByIdVO result = new Buy0008GetInfoByIdVO();
        result.setBillPO(buyRequestbuyBill);
        result.setItemPOList(buyRequestbuyBillItems);
        return result;
    }

    public File convertMultipartFileToFile(MultipartFile file) throws IOException {
        File convFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            System.out.println("File is empty or its size is zero, please check!");
        } else {
            InputStream inputStream = file.getInputStream();
            convFile = new File(file.getOriginalFilename());
            FileOutputStream fos = new FileOutputStream(convFile);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }
            fos.close();
            inputStream.close();
        }
        return convFile;
    }

    /*
     *  @Description 根据行号、列号定位cell获取值
     *  @param  cell
     *  @return  getCellValue
     *  @author  itw_lixd05
     */
    public static String getCellValue(Cell cell, XSSFWorkbook workbook) {
        String cellValue = "";
        if (cell == null) {
            return cellValue;
        }
        if (cell == null) {// 单元格为空设置cellStr为空串
            cellValue = "";
        } else if (cell.getCellType().equals(CellType.BOOLEAN)) {
            // 对布尔值的处理
            cellValue = String.valueOf(cell.getBooleanCellValue());
        } else if (cell.getCellType().equals(CellType.NUMERIC)) {
            // 对数字值的处理
            cellValue = cell.getNumericCellValue() + "";
            //如果最后两位是.0,就干掉，因为是默认把字符当成数字了
            if (!StringUtils.isEmpty(cellValue) &&cellValue.length() > 2) {
                String lastTwo = cellValue.substring(cellValue.length() - 2);
                if (lastTwo.equals(".0")) {
                    cellValue = cellValue.substring(0, cellValue.length() - 2);
                }
            }
        }else if (cell.getCellType().equals(CellType.FORMULA)) {
            FormulaEvaluator formulaEvaluator = new XSSFFormulaEvaluator((XSSFWorkbook) workbook);
            String cellFormula = cell.getCellFormula();
            // 执行公式，此处cell的值就是公式
            CellValue evaluate = formulaEvaluator.evaluate(cell);
            cellValue = evaluate.formatAsString();
        }
        else {
            // 其余按照字符串处理
            cellValue = cell.getStringCellValue();
        }
        return cellValue;
    }

    private BuyRequestbuyBillItem getBuyRequestBuyItem(XSSFRow row){
        BuyRequestbuyBillItem buyRequestbuyBillItem = new BuyRequestbuyBillItem();
        //项目编号
        XSSFCell cell = row.getCell(2);
        String cellValue = getCellValue(cell,new XSSFWorkbook());
        buyRequestbuyBillItem.setvProjectNo(cellValue);
        //项目简称
        cell = row.getCell(3);
        cellValue = getCellValue(cell,new XSSFWorkbook());
        buyRequestbuyBillItem.setvProjectDec(cellValue);
        //零件名称
        cell = row.getCell(4);
        cellValue = getCellValue(cell,new XSSFWorkbook());
        buyRequestbuyBillItem.setvSpaName(cellValue);
        //规格型号
        cell = row.getCell(5);
        cellValue = getCellValue(cell,new XSSFWorkbook());
        buyRequestbuyBillItem.setvSpaModel(cellValue);
        //推荐品牌
        cell = row.getCell(6);
        cellValue = getCellValue(cell,new XSSFWorkbook());
        buyRequestbuyBillItem.setvSpaBrand(cellValue);
        //数量
        cell = row.getCell(7);
        cellValue = getCellValue(cell,new XSSFWorkbook());
        buyRequestbuyBillItem.setnQty(new BigDecimal(cellValue));
        //单位
        cell = row.getCell(8);
        cellValue = getCellValue(cell,new XSSFWorkbook());
        buyRequestbuyBillItem.setvUnit(cellValue);
        //要求货期
        cell = row.getCell(9);
        cellValue = getCellValue(cell,new XSSFWorkbook());
        buyRequestbuyBillItem.setnDays(cellValue);
        //特殊说明
        cell = row.getCell(10);
        cellValue = getCellValue(cell,new XSSFWorkbook());
        buyRequestbuyBillItem.setRemark(cellValue);
        return buyRequestbuyBillItem;
    }
}
